<script>
// 结果列表模块
import { mapActions, mapMutations } from 'vuex';
import mapManager from '../mapManager.js';
import ShowTable from './showTable.js';
import QueryPrams from './QueryPrams';
import * as helps from '@/utils/helps';

export default {
  name: 'OverLapList',
  components: { QueryPrams },
  mixins: [ShowTable],
  props: {
    //查询服务地址
    service: {
      type: String,
      default: '',
    },
    //查询条件
    where: {
      type: String,
      default: '',
    },
    //分页大小
    pageSize: {
      type: Number,
      default: 10,
    },
    mapData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      allData: [
        {
          columns: [],
          data: [],
          total: 0,
        },
      ],
      //分页控件是否已初始化
      pageInited: false,
      //数据是否在加载
      loading: false,
      relLoading: false,
      serviceType: '',
      //当前分页数据
      pagedData: [],
      // 统计字段
      relChangeValue: '',
      relChangeSchema: [],
      isStartStatics: false,
      // 弹窗控制
      showQury: false,
      querySchema: [],
      queryLayer: [],
      filterName: '过滤显示',
      filterKey: 0, // 0 过滤，1 全部
      isFilter: false,
    };
  },
  watch: {
    service(newVal) {
      this.initQuery();
    },
    where(newVal) {
      this.initQuery();
    },
  },
  destroyed() {
    // this.setMapGeoJson({});
  },
  methods: {
    initQuery() {
      this.pageInited = false;
    },
    // 得到指定类型的地图
    getMapData(type) {
      return this.mapData.filter(item => item.num === type);
    },
    // 加载高亮图层
    showData(mapId, data) {
      this.$store.commit(`${mapId}/SET_MAP_GEOJSON`, { geojson: data, type: 'once' });
    },
    // wfs公共方法
    async commonWfsQuery(mapid, url, pageIndex, options) {
      const response = await this.$store.dispatch(`${mapid}/MAP_WFS_QUERY`, {
        url: url,
        pageIndex,
        pageSize: this.pageSize,
        options: {
          type: 'POST',
          ...options,
        },
      });
      return response;
    },
    // 分析接口
    changeQuery(url, data) {
      return this.$store.dispatch(`${this.finalMapData[0].mapId}/MAP_WPS_STARTCHANGES`, {
        url,
        ...data,
      });
    },
    // wfs查询
    async wfsQuery(pageIndex, options, isRender, startChangesOptions) {
      this.queryLayer = [];
      this.loading = true;
      this.serviceType = 'wfsQuery';
      this.finalMapData = this.getMapData(3);
      if (isRender) {
        this.allData = [
          {
            columns: [],
            data: [],
            total: 0,
          },
        ];
      }
      if (startChangesOptions) {
        this.startChangesOptions = startChangesOptions;
        if (startChangesOptions.relCrs) options.srsName = startChangesOptions.relCrs;
      }

      const url = new URL(this.service);
      const layersName = url.searchParams.get('typeName');
      this.queryLayer.push(layersName);
      const response = await this.commonWfsQuery(
        this.finalMapData[0].mapId,
        this.service,
        pageIndex,
        options
      );
      this.loading = false;
      this.pagedData = response;
      if (this.allData.length !== 0) {
        this.allData[0].columns = [];
        this.allData[0].data = [];
      }
      this.allData[0].title = '变化监测';
      this.allData[0].columns = this.getTableColumns(response);
      this.querySchema = this.allData[0].columns;
      this.allData[0].data = this.getTableRows(response);
      if (this.allData[0].total !== response.totalFeatures) {
        this.allData[0].total = response.totalFeatures;
        this.pageInited = true;
      }
    },
    // 变化查询
    dltbChanges(indexNum, options, isRender) {
      this.queryLayer = [];
      this.serviceType = 'statDltbChanges';
      this.loading = true;
      // 是否初始展示判断
      if (isRender) {
        this.allData = [
          {
            columns: [],
            data: [],
            total: 0,
          },
        ];
        if (this.$refs.page0) this.$refs.page0[0].currentPage = 1;
      }
      if (this.isStartStatics) {
        this.isStartStatics = false;
      }
      if (options) {
        this.startChangesOptions = options;
      }
      // 参数设置
      let data;
      this.queryLayer.push(this.startChangesOptions.layers);
      if (indexNum || this.relChangeValue === '') {
        this.relChangeValue === '';
        data = {
          path: this.startChangesOptions.layers,
          fieldMap: this.startChangesOptions.params,
          // destcrs: this.startChangesOptions.relCrs,
          destcrs: 'EPSG:2382',
          start: (indexNum - 1) * 10,
          end: 10,
        };
      } else {
        data = {
          path: this.startChangesOptions.layers,
          fieldMap: this.startChangesOptions.params,
          destcrs: 'EPSG:2382',
          getOne: this.relChangeValue,
        };
      }

      if (!this.finalMapData) this.finalMapData = this.getMapData(3);
      new Promise((resolve, reject) => {
        const hasList = this.changeQuery(this.service, data);
        resolve(hasList);
      }).then(res => {
        this.loading = false;
        if (res === '没有结果') {
          this.$Message.error(res);
        } else {
          const response = JSON.parse(res);
          this.allData[0].columns = [];
          this.allData[0].data = [];
          this.allData[0].title = '统计信息';
          if (response.arr) {
            this.staticsArray = [];
            this.allData[0].columns = this.getChangeTableColumns(response.arr);
            this.allData[0].data = this.getChangeTableData(response.arr);
            if (this.allData[0].total !== response.count) {
              this.allData[0].total = response.count;
            }
          } else {
            this.staticsArray = [...response.arr1, ...response.arr2];
            this.setStaticPage(1);
            if (this.allData[0].total !== this.staticsArray.length) {
              this.allData[0].total = this.staticsArray.length;
            }
          }
        }
      });
    },
    // 统计汇总分页计算
    setStaticPage(pageIndex) {
      let table;
      if (this.staticsArray.length < 10) {
        table = this.staticsArray;
      } else {
        table = this.staticsArray.slice((pageIndex - 1) * 10, (pageIndex - 1) * 10 + 10);
      }
      this.allData[0].columns = this.getChangeTableColumns(table);
      this.allData[0].data = this.getChangeTableData(table);
    },
    // 详细变换监测
    async startRelChanges(pageIndex, options) {
      this.relLoading = true;
      this.serviceType = 'startRelChanges';
      // 参数设置
      if (options.CQL_FILTER || options.cql_filter)
        this.cql_filter = options.CQL_FILTER ? options.CQL_FILTER : options.cql_filter;
      if (!this.finalMapData) this.finalMapData = this.getMapData(3);
      const response = await this.commonWfsQuery(
        this.finalMapData[0].mapId,
        this.service,
        pageIndex,
        options
      );
      this.relLoading = false;
      this.relPageData = response;
      if (this.allData[1]) {
        this.allData[1].columns = [];
        this.allData[1].data = [];
      } else {
        this.allData.push({
          columns: [],
          data: [],
          total: 0,
        });
      }
      this.allData[1].title = '详细分类信息';
      this.allData[1].columns = this.getTableColumns(response);
      this.querySchema = this.allData[1].columns;
      this.allData[1].data = this.getTableRows(response);
      if (this.allData[1].total !== response.totalFeatures) {
        this.allData[1].total = response.totalFeatures;
      }
    },
    // 搜索字段
    async searchValue(value) {
      if (value.indexOf(' ') !== 0 && value !== '') {
        const params = this.startChangesOptions.params.split(',');
        const encodeParams = "'%" + `${value}` + "%'";
        const response = await this.commonWfsQuery(this.finalMapData[0].mapId, this.service, 1, {
          cql_filter: `"${params[0]}" LIKE ` + encodeParams,
        });
        this.relChangeSchema = [];
        if (response.features.length !== 0) {
          response.features.forEach(feature => {
            if (
              this.relChangeSchema.filter(item => item === feature.properties[params[0]]).length ===
              0
            ) {
              this.relChangeSchema.push(feature.properties[params[0]]);
            }
          });
        }
      } else {
        this.relChangeSchema = [];
      }
      this.relChangeSchema = [...this.relChangeSchema];
    },
    // 统计汇总
    startStatics() {
      this.isStartStatics = true;
      if (this.relChangeValue === '') {
        this.dltbChanges(1, null, true);
      } else {
        this.dltbChanges(null, null, true);
      }
    },
    // 属性过滤
    filterGeoJson() {
      this.showQury = true;
    },
    // 得到属性进行查询
    getQueryOption(options) {
      this.isFilter = true;
      this.wfsQuery(1, options, true);
      this.filterOptions = options;
      this.showQury = false;
    },
    // 过滤结果
    filterLayers() {
      this.filterName === '过滤显示'
        ? (this.filterName = '全部显示')
        : (this.filterName = '过滤显示');
      this.finalMapData = this.getMapData(3);
      if (this.filterKey === 0) {
        // 隐藏原始图层
        if (this.isFilter) {
          this.$store.getters[`${this.finalMapData[0].mapId}/ogcLayers`][0].setParams(
            this.filterOptions
          );
        } else {
          this.$store.getters[`${this.finalMapData[0].mapId}/ogcLayers`][0].setParams({
            cql_filter: this.cql_filter,
          });
        }
        this.filterKey = 1;
      } else {
        // this.$store.getters[`${this.finalMapData[0].mapId}/ogcLayers`][0].setParams({
        //   cql_filter: '1>0',
        // });
        delete this.$store.getters[`${this.finalMapData[0].mapId}/ogcLayers`][0].wmsParams
          .cql_filter;
        this.$store.getters[`${this.finalMapData[0].mapId}/ogcLayers`][0].redraw();
        this.filterKey = 0;
      }
      window.dispatchEvent(new Event('resize'));
    },
    //定位到要素
    zoomToFeature(item) {
      const state = {
        wfsQuery() {
          let feature = this.pagedData.features.find(
            p => p.properties.gid == item.gid && p.properties.gid1 == item.gid1
          );
          for (let key in this.mapData) {
            this.showData(this.mapData[key].mapId, feature);
          }
          // this.showData(this.mapData[2].mapId, feature);
          // // 查询分析图层并高亮
          // this.mapData.forEach(async data => {
          //   if (data.num === 1 || data.num === 2) {
          //     const url = new URL(
          //       this.startChangesOptions.selectLayerData[
          //         `layer${data.num}`
          //       ][0].services[0].servicesurl
          //     );
          //     const queryUrl = url.origin + url.pathname;
          //     const layerName = url.searchParams.get('layers');
          //     const relUrl = `${queryUrl}?typeName=${layerName}`;
          //     const response = await this.commonWfsQuery(data.mapId, relUrl, 1, {
          //       CQL_FILTER: `"gid" = '${data.num === 1 ? item.gid : item.over_gid}'`,
          //     });
          //     this.showData(this.mapData[data.num - 1].mapId, response);
          //   }
          // });
        },
        statDltbChanges() {
          this.isFilter = false;
          this.getOne = item.changeType.split('变');
          this.params = this.startChangesOptions.params.split(',');
          this.startRelChanges(1, {
            CQL_FILTER: `"${this.params[0]}" = '${this.getOne[0]}' and "${this.params[1]}" = '${
              this.getOne[1]
            }'`,
          });
          if (this.$refs.page1 && this.$refs.page1.length !== 0)
            this.$refs.page1[0].currentPage = 1;
        },
        startRelChanges() {
          let feature = this.relPageData.features.find(p => p.id == item.id);
          // 高亮叠加图层
          this.showData(this.mapData[2].mapId, feature);
          // 查询分析图层并高亮
          this.mapData.forEach(async data => {
            if (data.num === 1 || data.num === 2) {
              const url = new URL(
                this.startChangesOptions.selectLayerData[
                  `layer${data.num}`
                ][0].services[0].servicesurl
              );
              const queryUrl = url.origin + url.pathname;
              let layerName = url.searchParams.get('layers');
              if (!layerName) layerName = url.searchParams.get('typeName');
              const relUrl = `${queryUrl}?typeName=${layerName}`;
              const response = await this.commonWfsQuery(data.mapId, relUrl, 1, {
                CQL_FILTER: `"gid" = '${data.num === 1 ? item.gid1 : item.over_gid}'`,
              });
              this.showData(this.mapData[data.num - 1].mapId, response);
            }
          });
        },
      };
      if (this.serviceType) state[this.serviceType].call(this);
    },
    //分页查询
    queryFeatures(pageIdx) {
      const state = {
        wfsQuery() {
          this.wfsQuery(pageIdx);
        },
        statDltbChanges() {
          if (this.relChangeValue === '') {
            this.dltbChanges(pageIdx);
          } else {
            if (this.staticsArray.length !== 0) {
              this.setStaticPage(pageIdx);
            } else {
              this.dltbChanges(pageIdx);
            }
          }
        },
        startRelChanges() {
          this.startRelChanges(pageIdx, {
            CQL_FILTER: `"${this.params[0]}" = '${this.getOne[0]}' and "${this.params[1]}" = '${
              this.getOne[1]
            }'`,
          });
        },
      };
      if (this.serviceType) state[this.serviceType].call(this);
    },
    changeType(index) {
      if (index === 0 && this.serviceType !== 'wfsQuery') {
        this.serviceType = 'statDltbChanges';
      } else {
        if (this.serviceType !== 'wfsQuery') {
          this.serviceType = 'startRelChanges';
        }
      }
    },
  },
};
</script>

<template>
  <div class="datav-overlaplist-wrapper">
    <div
      v-for="(item,index) in allData"
      :key="index"
      :class="allData.length===1?'list-one-table':'list-two-table'"
      @mouseenter="changeType(index)">
      <div class="change-title clearfix">
        <h4>{{ item.title }}</h4>
        <div
          v-if="item.title==='统计信息'"
          class="change-fun">
          <AutoComplete
            v-model="relChangeValue"
            :data="relChangeSchema"
            placeholder="请输入字段"
            style="width:150px"
            size="small"
            transfer
            @on-search="searchValue"></AutoComplete>
          <Button
            type="primary"
            size="small"
            @click="startStatics">统计汇总</Button>
        </div>
        <div
          v-if="item.title==='变化监测' || item.title==='详细分类信息'"
          class="change-fun">
          <Button
            v-if="item.title==='变化监测'"
            type="primary"
            size="small"
            @click="filterGeoJson">属性过滤</Button>
          <Button
            type="success"
            size="small"
            @click="filterLayers">{{ filterName }}</Button>
        </div>
      </div>
      <Table
        :columns="item.columns"
        :data="item.data"
        :loading="serviceType!=='startRelChanges'?loading:relLoading"
        height="167"
        size="small"
        highlight-row
        border
        stripe
        show-header
        @on-current-change="zoomToFeature">
      </Table>
      <div class="overlap-table-page">
        <Page
          :ref="`page${index}`"
          :total="item.total"
          size="small"
          show-total
          @on-change="queryFeatures">
        </Page>
      </div>
    </div>
    <Modal
      v-model="showQury"
      title="属性过滤"
      footer-hide
    >
      <QueryPrams
        :query-layer="queryLayer"
        :query-schema="querySchema"
        @on-get-queryOption="getQueryOption"></QueryPrams>
    </Modal>
  </div>
</template>

<style lang="less" scoped>
.datav-overlaplist-wrapper {
  .change-title {
    display: block;
    margin-bottom: 2px;
    h4 {
      margin-right: 10px;
      height: 25px;
      line-height: 25px;
      color: #57a3f3;
      float: left;
    }
    .change-title {
    }
  }

  .list-one-table {
    width: 100%;
    height: 100%;
  }

  .list-two-table {
    float: left;
    height: 100%;
  }

  .list-two-table:first-child {
    margin-left: 0.5%;
    margin-right: 1%;
    width: 35%;
  }
  .list-two-table:last-child {
    width: 62%;
  }

  .overlap-table-page {
    margin: 3px;
    margin-top: 5px;
    .k-page.mini .k-page-prev,
    .k-page.mini .k-page-next,
    .k-page.mini .k-page-item {
      min-width: 22px;
      height: 22px;
    }
  }
}
</style>
